package com.tomato.security.util;

import com.tomato.security.domain.LoginUser;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Security 工具类
 *
 * @author lizhifu
 * @since 2022/12/30
 */
public class SecurityFrameworkUtil {

	/**
	 * 获取当前用户
	 * @return 当前用户
	 */
	@Nullable
	public static LoginUser getLoginUser() {
		Authentication authentication = getAuthentication();
		if (authentication == null) {
			return null;
		}
		return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
	}

	/**
	 * 获得当前认证信息
	 * @return 认证信息
	 */
	public static Authentication getAuthentication() {
		SecurityContext context = SecurityContextHolder.getContext();
		if (context == null) {
			return null;
		}
		return context.getAuthentication();
	}

}
